import { ref } from 'vue'
import Sortable from 'sortablejs'
import { ElMessage } from 'element-plus'
import i18n from '@/i18n'

export const tableRef = ref(null)

export const initSortable = (tableData, cb) => {
  // console.log('xxx', tableRef.value.$el)
  const el = tableRef.value.$el.querySelectorAll('.el-table__body > tbody')[0]

  // 1.拖拽元素 2.配置对象
  Sortable.create(el, {
    // 拖拽时类名
    ghostClass: 'sortable-ghost',
    // 拖拽结束的回调
    onEnd (event) {
      // TODO 调用接口更新排名
      const { newIndex, oldIndex } = event
      console.log(
        '接口参数',
        tableData.value[newIndex].ranking,
        tableData.value[oldIndex].ranking
      )
      ElMessage.success(i18n.global.t('msg.article.sortSuccess'))
      // 刷新表单
      tableData.value = []
      cb && cb()
    }
  })
}
